<?php

include('../config.php');

function check_security($levels) {
    if (!is_array($levels))
        $levels = array($levels);
    if (!base_obj::security($levels)) {
        $result = array();
        $result['result'] = 0;
        $result['error'] = NO_RIGHTS;
        echo json_encode($result);
        exit;
    }
}

if (empty($_REQUEST['action'])) {
    $result = array();
    $result['result'] = 0;
    $result['error'] = 'no action';
    echo json_encode($result);
    exit;
} else {
    $action = $_REQUEST['action'];
}

if (empty($_REQUEST['module'])) {
    $result = array();
    $result['result'] = 0;
    $result['error'] = 'no module';
    echo json_encode($result);
    exit;
}

$module_folders = explode('/', $_REQUEST['module']);
$pathToModule = '';
for ($i = 0; $i < count($module_folders) - 1; $i++) {
    $pathToModule .= $module_folders[$i] . '/';
}
$nameOfModule = str_replace('/', '_', $pathToModule) . $module_folders[count($module_folders) - 1] . '_module';

$MODULE = PATH_TO_MODULES . $pathToModule . $nameOfModule . '.php';

if (file_exists($MODULE)) {
    include $MODULE;
    $module = new $nameOfModule();

    if (method_exists($module, $action)) {
        
        $securityLevel = $module->{'securityLevel_' . $action};
        if (isset($securityLevel)){
            check_security($securityLevel);
        }
        
        $module_result = $module->$action($_REQUEST['params']);

        if (error_obj::isError($module_result)) {
            $result = array();
            $result['result'] = 0;
            $result['error'] = UNEXCEPTED;
            $result['error_data'] = (array) $module_result;
            echo json_encode($result);
            exit;
        } else {
            $result = array();
            $result['result'] = 1;
            $result['data'] = $module_result;
            echo json_encode($result);
            exit;
        }
    } else {
        $result = array();
        $result['result'] = 0;
        $result['error'] = 'unknown action';
        echo json_encode($result);
        exit;
    }
} else {
    $result = array();
    $result['result'] = 0;
    $result['error'] = 'unknown module';
    echo json_encode($result);
    exit;
}
?>
